const {ccclass, property} = cc._decorator;
import Seat from './Seat';



@ccclass
export default class MJRoom extends cc.Component {

    
    
    /**左上角房间号文字节点 */
    lblRoomNo: cc.Label = null;


    /**左上角时间的文字节点 */
    timeLabel: cc.Label = null;

    /**prepare节点下四个玩家的Seat脚本数组 */
    seats: Seat[] = [];

    /**game节点下四个玩家的Seat脚本数组 */
    seats2: Seat[] = [];

    /**语音消息队列 */
    voiceMsgQueue: cc.seat[] = [];


    /**当前是哪个玩家使用语音的ID */
    playingSeat = null;

    /**音频播放的结束时间戳 */
    lastPlayTime = null;

    /**当前时间的分 */
    lastMinute = (new Date()).getMinutes();

    onLoad() {
        if(!cc.vv){
            return;
        }
        
        this.initView();
        this.initSeats();
        this.initEventHandlers();

        /**设置按钮点击 */
        const btnSettings = cc.find('Canvas/btn_settings');
        cc.vv.utils.addClickEvent(btnSettings, this.node, 'MJRoom', 'onBtnSettingsClicked');

        /**返回大厅按钮点击 */
        const btnBack = cc.find('Canvas/prepare/btnBack');
        cc.vv.utils.addClickEvent(btnBack, this.node, 'MJRoom', 'onBtnBackClicked');

        /**解散房间按钮点击 */
        const btnDissolve = cc.find('Canvas/prepare/btnDissolve');
        cc.vv.utils.addClickEvent(btnDissolve, this.node, 'MJRoom', 'onBtnDissolveClicked');
        
        /**退出房间按钮的点击 */
        const btnExit = cc.find('Canvas/prepare/btnExit');
        cc.vv.utils.addClickEvent(btnExit, this.node, 'MJRoom', 'onBtnExitClicked');

    }

    initView(){
        const prepare = this.node.getChildByName('prepare');
        const seats = prepare.getChildByName('seats');
        for(let i = 0; i < seats.childrenCount; i++){
            this.seats.push(seats.children[i].getComponent(Seat));
        }

        this.refreshBtns();

        this.lblRoomNo = cc.find("Canvas/infobar/Z_room_txt/New Label").getComponent(cc.Label);
        this.timeLabel = cc.find("Canvas/infobar/time").getComponent(cc.Label);
        this.lblRoomNo.string = cc.vv.gameNetMgr.roomId;
        const gameChild = this.node.getChildByName("game");

        for(let key in cc.vv.directions){
            const sideNode = gameChild.getChildByName(cc.vv.directions[key]);
            const seat = sideNode.getChildByName('seat');
            
            this.seats2.push(seat.getComponent(Seat));
        }

        /**邀请微信好友按钮 */
        const btnWechat = cc.find("Canvas/prepare/btnWeichat");
        if(btnWechat){
            cc.vv.utils.addClickEvent(btnWechat, this.node, 'MJRoom', 'onBtnWechatClicked');
        }

        /**牌桌中间游戏类型的容器 */
        const titles = cc.find('Canvas/typeTitle');
        for(let i = 0; i < titles.childrenCount; i++){
            titles.children[i].active = false;
        }

        
        titles.getChildByName(cc.vv.gameNetMgr.conf.type || 'xzdd').active = true;
        
    }

    /**更新解散房间、邀请微信好友、返回大厅按钮 */
    refreshBtns(){
        const prepare = this.node.getChildByName('prepare');
        /**解散房间节点 */
        const btnExit = prepare.getChildByName('btnExit');
        /**解散房间节点 */
        const btnDispress = prepare.getChildByName('btnDissolve');
        /**邀请微信好友节点 */
        const btnWechat = prepare.getChildByName('btnWeichat');
        /**返回大厅节点 */
        const btnBack = prepare.getChildByName('btnBack');
        const isIdle = cc.vv.gameNetMgr.numOfGames == 0;

        btnExit.active = !cc.vv.gameNetMgr.isOwner() && isIdle;
        btnDispress.active = cc.vv.gameNetMgr.isOwner() && isIdle;

        btnWechat.active = isIdle;
        btnBack.active = isIdle;
    }


    /**邀请微信好友的点击事件（分享） */
    onBtnWechatClicked(){
        let title = '<血战到底>';
        if(cc.vv.gameNetMgr.conf.type == 'xlch'){
            title = '<血流成河>';
        }
        cc.vv.anysdkMgr.share('天天麻将' + title, '房号:' + cc.vv.gameNetMgr.roomId + ' 玩法:' + cc.vv.gameNetMgr.getWanfa());
    }


    /**更新玩家座位上的各种信息 */
    initSeats(){
        const seats = cc.vv.gameNetMgr.seats;
        seats.forEach((item, index) => {
            this.initSingleSeat(item);
        });
    }

    /**更新玩家座位上的各种信息 */
    initSingleSeat(seat: cc.seat){
        const index = cc.vv.gameNetMgr.getLocalIndex(seat.seatIndex);
        const isOffline = !seat.online;
        const isZhuang = seat.seatIndex == cc.vv.gameNetMgr.button;

        this.seats[index].setInfo(seat.name, seat.score);
        this.seats[index].setReady(seat.ready);
        this.seats[index].setOffline(isOffline);
        this.seats[index].setID(seat.userId);
        this.seats[index].setVoicemsg(false);

        this.seats2[index].setInfo(seat.name, seat.score);
        this.seats2[index].setZhuang(isZhuang);
        this.seats2[index].setOffline(isOffline);
        this.seats2[index].setID(seat.userId);
        this.seats2[index].setVoicemsg(false);
        this.seats2[index].refreshXuanPaiState(); 
    }

    /**初始化各种事件监听 */
    initEventHandlers(){

        this.node.on(cc.vv.game_event_map.NEW_USER, (data) => {
            this.initSingleSeat(data.detail);
        });

        this.node.on(cc.vv.game_event_map.USER_STATE_CHANGED, (data) => {
            this.initSingleSeat(data.detail);
        });

        this.node.on(cc.vv.game_event_map.GAME_BEGIN, (data) => {
            this.refreshBtns();
            this.initSeats();
        });

        this.node.on(cc.vv.game_event_map.GAME_NUM, (data) => {
            this.refreshBtns();
        });

        this.node.on(cc.vv.game_event_map.GAME_HUANPAI, (data) => {
            this.seats2.forEach((item, index) => {
                item.refreshXuanPaiState();
            });
        });

        this.node.on(cc.vv.game_event_map.HUANPAI_NOTIFY, (data) => {
            const idx = data.detail.seatIndex;
            const localIdx = cc.vv.gameNetMgr.getLocalIndex(idx);
            this.seats2[localIdx].refreshXuanPaiState();
        });

        this.node.on(cc.vv.game_event_map.GAME_HUANPAI_OVER, (data) => {
            this.seats2.forEach((item, index) => {
                item.refreshXuanPaiState();
            });
        });

        this.node.on(cc.vv.game_event_map.VOICE_MSG, (data) => {
            this.voiceMsgQueue.push(data.detail);
            this.playVoice();
        });

        this.node.on(cc.vv.game_event_map.CHAT_PUSH, (data) => {
            const data1 = data.detail;
            const idx = cc.vv.gameNetMgr.getSeatIndexById(data1.sender);
            const localIndex = cc.vv.gameNetMgr.getLocalIndex(idx);
            this.seats[localIndex].setChat(data1.content);
            this.seats2[localIndex].setChat(data1.content);
        });

        this.node.on(cc.vv.game_event_map.EMOJI_PUSH, (data) => {
            const data1 = data.detail;
            const idx = cc.vv.gameNetMgr.getSeatIndexById(data1.sender);
            const localIndex = cc.vv.gameNetMgr.getLocalIndex(idx);
            this.seats[localIndex].setEmoji(data1.content);
            this.seats2[localIndex].setEmoji(data1.content);
        });

        
        this.node.on(cc.vv.game_event_map.QUICK_CHAT_PUSH, (data) => {
            const data1 = data.detail;
            const idx = cc.vv.gameNetMgr.getSeatIndexById(data1.sender);
            const localIndex = cc.vv.gameNetMgr.getLocalIndex(idx);
            const index = data1.content;
            const info = cc.vv.chat.getQuickChatInfo(index);
            this.seats[localIndex].setChat(info.content);
            this.seats2[localIndex].setChat(info.content);
            cc.vv.audioMgr.playSFX(info.sound);
        });

    }



    /**播放录音 */
    playVoice(){
        if(this.playingSeat == null && this.voiceMsgQueue.length){
            const data = this.voiceMsgQueue.shift();
            const idx = cc.vv.gameNetMgr.getSeatIndexById(data.sender);
            const localIndex = cc.vv.gameNetMgr.getLocalIndex(idx);
            this.playingSeat = localIndex;
            this.seats[localIndex].setVoicemsg(true);
            this.seats2[localIndex].setVoicemsg(true);

            const msgInfo = JSON.parse(data.content);
            const msgfile = 'voicemsg.amr';
            cc.vv.voiceMgr.writeVoice(msgfile, msgInfo.msg);
            cc.vv.voiceMgr.play(msgfile);
            this.lastPlayTime = Date.now() + msgInfo.time + 200;
        }
    }

    update(dt: number){
        // 更新左上角的时间
        const minutes = Math.floor(Date.now() / 1000 / 60);
        if(this.lastMinute != minutes){
            this.lastMinute = minutes;
            const date = new Date();
            const h = date.getHours();
            let hours = '';
            hours = h > 10 ? h.toString() : '0' + h;
            const m = date.getMinutes();
            let minute = '';
            minute = m > 10 ? minute.toString() : '0' + minute;
            this.timeLabel.string = h + ':' + m;
        }

        // 播放音频队列
        if(this.lastPlayTime != null){
            if(Date.now() > this.lastPlayTime){
                this.onPlayerOver();
                this.lastPlayTime = null;
            }
        }
        else{
            this.playVoice();
        }
    }

    /**录音播放结束后(隐藏UI、更新状态) */
    onPlayerOver(){
        cc.vv.audioMgr.resumeAll();
        const localIndex = this.playingSeat;
        this.playingSeat = null;
        this.seats[localIndex].setVoicemsg(false);
        this.seats2[localIndex].setVoicemsg(false);
    }


    /**设置按钮的点击事件 */
    onBtnSettingsClicked(){
        cc.vv.popupMgr.showSettings();
    }

    onDestroy(){
        (!cc.vv.debug) && cc.vv.voiceMgr.stop();
    }

    /**返回大厅按钮的点击事件 */
    onBtnBackClicked(){
        cc.vv.alert.show('返回大厅', '返回大厅房间仍会保留，快去邀请大伙来玩吧！', () => {
            cc.vv.wc.show('再整返回游戏大厅');
            cc.director.loadScene('hall');
        });
    }

    /**解散房间按钮的点击事件 */
    onBtnDissolveClicked(){
        cc.vv.alert.show('解散房间', '解散房间不扣房卡，是否确定解散？', () => {
            cc.vv.net.send(cc.vv.game_event_map.DISPRESS);
        });
    }

    /**退出房间按钮的点击事件 */
    onBtnExitClicked(){
        cc.vv.net.send(cc.vv.game_event_map.EXIT);
    }
}


